﻿/*

License:

    PDF UPLOAD METADATA EXTRACTOR for SharePoint 2013
    Copyright (C) 2012  Ingo Karstein

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

See my blog:
    http://blog.karstein-consulting.com
    
This project uses the iTextSharp v4.1.6 library that is licensed under LGPL and is published here:
    
    http://nuget.org/packages/iTextSharp-LGPL
    
    In Visual Studio 2012 just install iTextSharp v4.1.6 with NuGet. Open the "Package Manager Console"
    and type in "Install-Package iTextSharp-LGPL"
    
    http://itextsharp.svn.sourceforge.net/viewvc/itextsharp/tags/iTextSharp_4_1_6/

*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using iTextSharp.text.pdf;
using System.Diagnostics;

namespace ik.SharePoint2013.PDFUploadMetadataExtractor
{
    class ListItemEventReceiver : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);

            Debugger.Launch();

            try
            {
                SPFile f = properties.ListItem.File;
                if( f.Name.EndsWith(".pdf", StringComparison.InvariantCultureIgnoreCase) )
                {
                    byte[] b = f.OpenBinary();

                    PdfReader r = new PdfReader(b);

                    if( !string.IsNullOrEmpty((string)r.Info["Title"]) )
                    {
                        f.Item[SPBuiltInFieldId.Title] = r.Info["Title"];
                        f.Item.SystemUpdate();
                    }
                }
            }
            catch
            {
            }
        }
    }
}
